<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="keywords" content="anhoder的进阶日志">
<meta name="description" content="一川烟草，满城风絮。">
<meta name="theme-color" content="#000">
<title>Git补坑 | anhoder的进阶日志</title>
<link rel="shortcut icon" href="/favicon.ico?v=1640406618472">
<link rel="stylesheet" href="/media/css/pisces.css">
<link rel="stylesheet" href="/media/fonts/font-awesome.css">
<link
  href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Rosario:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext"
  rel="stylesheet" type="text/css">

<link href="/media/hljs/styles/androidstudio.css"
  rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/themes/green/pace-theme-minimal.css" rel="stylesheet" />

<link rel="stylesheet" href="/styles/main.css">

<script src="/media/hljs/highlight.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/velocity-animate@1.5.0/velocity.ui.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css"
  integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">


<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js"
  integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js"
  integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous"
  onload="renderMathInElement(document.body);"></script>



<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-161423102-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() { dataLayer.push(arguments); }
  gtag('js', new Date());

  gtag('config', 'UA-161423102-1');
</script>


<script>
  var _hmt = _hmt || [];
  (function () {
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?bdf14d3cd277bc2dfa9f84d19b36a686";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>


  <meta name="description" content="Git补坑" />
  <meta name="keywords" content="git" />
</head>

<body>
  <div class="head-top-line"></div>
  <div class="header-box">
    
<div class="pisces">
  <header class="header  ">
    <div class="blog-header box-shadow-wrapper bg-color " id="header">
      <div class="nav-toggle" id="nav_toggle">
        <div class="toggle-box">
          <div class="line line-top"></div>
          <div class="line line-center"></div>
          <div class="line line-bottom"></div>
        </div>
      </div>
      <div class="site-meta">       
        <div class="site-title">
          
            <a href="/" class="brand">
              <span>anhoder的进阶日志</span>
            </a>  
          
        </div>
        
          <p class="subtitle">太阳不热，糖也正适合。</p>
        
      </div>
      <nav class="site-nav" id="site_nav">
        <ul id="nav_ul">
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/" target="_self">
                    <i class="fa fa-home"></i> 首页
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/archives/" target="_self">
                    <i class="fa fa-archive"></i> 归档
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/tags/" target="_self">
                    <i class="fa fa-tags"></i> 标签
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/post/about/" target="_self">
                    <i class="fa fa-user"></i> 关于
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="https://github.com/anhoder/" target="_blank">
                    <i class="fa fa-github"></i> GitHub
                  </a>
                
              
            </li>
          
            
            
            <li class="nav-item ">
              
              
                
                  <a href="/media/excalidraw/" target="_self">
                    <i class="fa fa-picture-o"></i> 制作手绘图
                  </a>
                
              
            </li>
          
          
          
        </ul>
      </nav>
    </div>
  </header>
</div>

<script type="text/javascript"> 
 
  let showNav = true;

  let navToggle = document.querySelector('#nav_toggle'),
  siteNav = document.querySelector('#site_nav');
  
  function navClick() {
    let sideBar = document.querySelector('.sidebar');
    let navUl = document.querySelector('#nav_ul');
    navToggle.classList.toggle('nav-toggle-active');
    siteNav.classList.toggle('nav-menu-active');
    if (siteNav.classList.contains('nav-menu-active')) {
      siteNav.style = "height: " + (navUl.children.length * 42) +"px !important";
    } else {
      siteNav.style = "";
    }
  }

  navToggle.addEventListener('click',navClick);  
</script>
  </div>
  <div class="main-continer">
    
    <div
      class="section-layout pisces ">
      <div class="section-layout-wrapper">
        

<div class="sidebar">
  
    <div class="sidebar-box box-shadow-wrapper bg-color right-motion" id="sidebar">
      
        <div class="post-list-sidebar">
          <div class="sidebar-title">
            <span id="tocSideBar" class="sidebar-title-item sidebar-title-active language" data-lan="index">文章目录</span>
            <span id="metaSideBar" class="sidebar-title-item language" data-lan="preview">站点概览</span>
          </div>
        </div>
      
      <div class="sidebar-body pisces" id="sidebar_body">
        
          
            <div class="post-side-meta" id="post_side_meta">
              
<div class="sidebar-wrapper box-shadow-wrapper bg-color">
  <div class="sidebar-item">
    <img class="site-author-image right-motion" src="/images/avatar.png"/>
    <p class="site-author-name">anhoder</p>
    
  </div>
  <div class="sidebar-item side-item-stat right-motion">
    <div class="sidebar-item-box">
      <a href="/archives/">
        
        <span class="site-item-stat-count">94</span>
        <span class="site-item-stat-name language" data-lan="article">文章</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="category">分类</span>
      </a>
    </div>
    <div class="sidebar-item-box">
      <a href="/tags/">
        <span class="site-item-stat-count">27</span>
        <span class="site-item-stat-name language" data-lan="tag">标签</span>
      </a>
    </div>
  </div>
  
    
  
  
    <div class="sidebar-item sidebar-item-social">
      <div class="social-item">
        
          
            <a href="https://github.com/anhoder">
              <i class="fa fa-github-alt" title="GitHub"></i>
            </a>
          
            <a href="https://twitter.com/Alan_Albert_">
              <i class="fa fa-twitter" title="Twitter"></i>
            </a>
          
            <a href="https://weibo.com/u/5794659803">
              <i class="fa fa-weibo" title="Weibo"></i>
            </a>
          
            <a href="mailto:anhoder@88.com">
              <i class="fa fa-envelope" title="Email"></i>
            </a>
          
            <a href="https://stackoverflow.com/users/9723854/alan">
              <i class="fa fa-stack-overflow" title="StackOverflow"></i>
            </a>
          
        
        
          
            <a class="social-img" href="#">
              <img src="/media/images/custom-array-imgSocials-1617614181832-socialImg.png" />
              <i class="fa fa-weixin" title="微信公众号" ></i>
            </a>
          
        
      </div>
    </div>
  

  



</div>
            </div>
            <div class="post-toc sidebar-body-active" id="post_toc" style="opacity: 1;">
              <div class="toc-box right-motion">
  <div class="toc-wrapper  auto"
    id="toc_wrapper">
    <ul class="markdownIt-TOC">
<li>
<ul>
<li><a href="#%E4%B8%80-%E5%AE%89%E8%A3%85git">一、安装Git</a>
<ul>
<li><a href="#windows">Windows</a></li>
<li><a href="#mac">Mac</a></li>
<li><a href="#linux">Linux</a></li>
</ul>
</li>
<li><a href="#%E4%BA%8C-git%E7%9B%B8%E5%85%B3%E6%93%8D%E4%BD%9C">二、Git相关操作</a>
<ul>
<li><a href="#1%E5%88%9B%E5%BB%BA%E7%89%88%E6%9C%AC%E5%BA%93%E4%BB%93%E5%BA%93repository">1.创建版本库(仓库，Repository)</a></li>
<li><a href="#2%E6%B7%BB%E5%8A%A0%E6%96%87%E4%BB%B6%E5%88%B0%E7%89%88%E6%9C%AC%E5%BA%93">2.添加文件到版本库</a></li>
<li><a href="#3%E6%8F%90%E4%BA%A4%E6%96%87%E4%BB%B6%E5%88%B0%E7%89%88%E6%9C%AC%E5%BA%93">3.提交文件到版本库</a></li>
<li><a href="#4%E6%9F%A5%E7%9C%8B%E6%8F%90%E4%BA%A4%E6%97%A5%E5%BF%97">4.查看提交日志</a></li>
<li><a href="#5%E9%87%8D%E7%BD%AE%E7%89%88%E6%9C%AC">5.重置版本</a></li>
<li><a href="#6%E5%B7%A5%E4%BD%9C%E5%8C%BA-working-copy%E5%92%8C%E6%9A%82%E5%AD%98%E5%8C%BAstaging-copy">6.工作区 （working copy）和暂存区（staging copy）</a></li>
<li><a href="#7%E6%9F%A5%E7%9C%8B%E7%8A%B6%E6%80%81">7.查看状态</a></li>
<li><a href="#8%E6%9F%A5%E7%9C%8B%E5%B7%AE%E5%BC%82">8.查看差异</a></li>
<li><a href="#9%E6%92%A4%E9%94%80%E4%BF%AE%E6%94%B9">9.撤销修改</a></li>
<li><a href="#10%E5%88%A0%E9%99%A4%E6%96%87%E4%BB%B6">10.删除文件</a></li>
<li><a href="#11%E6%B7%BB%E5%8A%A0%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93">11.添加远程仓库</a></li>
<li><a href="#11%E4%BB%8E%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E5%85%8B%E9%9A%86">11.从远程仓库克隆</a></li>
<li><a href="#12%E5%88%86%E6%94%AF%E7%AE%A1%E7%90%86">12.分支管理</a></li>
<li><a href="#13%E5%88%86%E6%94%AF%E7%AE%A1%E7%90%86%E7%AD%96%E7%95%A5">13.分支管理策略</a></li>
<li><a href="#14%E9%9A%90%E8%97%8F%E6%94%B9%E5%8F%98">14.隐藏改变</a></li>
<li><a href="#15%E6%A0%87%E7%AD%BE%E7%AE%A1%E7%90%86">15.标签管理</a></li>
<li><a href="#16%E5%A4%9A%E4%BA%BA%E5%8D%8F%E4%BD%9C%E7%9A%84%E5%B7%A5%E4%BD%9C%E6%B5%81%E7%A8%8B">16.多人协作的工作流程</a></li>
</ul>
</li>
<li><a href="#%E4%B8%89-%E6%80%BB%E7%BB%93">三、总结</a></li>
<li><a href="#%E5%9B%9B-%E5%AE%9E%E9%99%85%E4%BD%BF%E7%94%A8">四、实际使用</a>
<ul>
<li><a href="#1-%E5%9C%A8github%E4%B8%8A%E4%BF%AE%E6%94%B9%E4%BB%96%E4%BA%BA%E9%A1%B9%E7%9B%AE%E7%9A%84%E4%BB%A3%E7%A0%81">1、在GitHub上，修改他人项目的代码</a></li>
<li><a href="#2-pull-request%E8%A2%AB%E5%90%88%E5%B9%B6%E5%90%8E">2、Pull Request被合并后</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  </div>
</div>

<script>

  let lastTop = 0, lList = [], hList = [], postBody, lastIndex = -1;
  let active = 'active-show', activeClass = 'active-current';
  let tocWrapper = document.querySelector('#toc_wrapper');
  let tocContent = tocWrapper.children[0];
  let autoNumber = tocWrapper && tocWrapper.classList.contains('auto-number');

  function addTocNumber(elem, deep) {
    if (!elem) {
      return;
    }
    let prop = elem.__proto__;

    if (prop === HTMLUListElement.prototype) {
      for (let i = 0; i < elem.children.length; i++) {
        addTocNumber(elem.children[i], deep + (i + 1) + '.');
      }
    } else if (prop === HTMLLIElement.prototype) {
      // 保存li元素
      if (elem.children[0] && elem.children[0].__proto__ === HTMLAnchorElement.prototype) {
        lList.push(elem);
      }
      for (let i = 0; i < elem.children.length; i++) {
        let cur = elem.children[i];
        if (cur.__proto__ === HTMLAnchorElement.prototype) {
          if (autoNumber) {
            cur.text = deep + ' ' + cur.text;
          }
        } else if (cur.__proto__ === HTMLUListElement.prototype) {
          addTocNumber(cur, deep);
        }
      }
    }
  }

  function removeParentActiveClass() {
    let parents = tocContent.querySelectorAll('.' + active)
    parents.forEach(function (elem) {
      elem.classList.remove(active);
    });
  }

  function addActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.add(activeClass);
    }
  }

  function removeActiveClass(index) {
    if (index >= 0 && index < hList.length) {
      lList[index].classList.remove(activeClass);
    }
  }

  function addActiveLiElemment(elem, parent) {
    if (!elem || elem === parent) {
      return;
    } else {
      if (elem.__proto__ === HTMLLIElement.prototype) {
        elem.classList.add(active);
      }
      addActiveLiElemment(elem.parentElement, parent);
    }
  }

  function showToc() {
    if (tocWrapper) {
      postBody = document.querySelector('#post_body');
      for (let i = 0; i < postBody.children.length; i++) {
        if (postBody.children[i].__proto__ === HTMLHeadingElement.prototype) {
          hList.push(postBody.children[i]);
        }
      }
      if (tocWrapper.classList.contains('compress')) {
        tocContent.classList.add('closed');
      } else if (tocWrapper.classList.contains('no_compress')) {
        tocContent.classList.add('expanded');
      } else {
        if (hList.length > 10) {
          active = 'active-hidden'
          tocContent.classList.add('closed');
        } else {
          tocContent.classList.add('expanded');
        }
      }
    }
  }

  (function () {
    // 处理不是从#一级标题开始目录
    if (tocContent.children.length === 1 && tocContent.children[0].__proto__ === HTMLLIElement.prototype) {
      let con = tocContent.children[0].children[0];
      tocContent.innerHTML = con.innerHTML;
    }
    let markdownItTOC = document.querySelector('.markdownIt-TOC');
    let innerHeight = window.innerHeight;
    markdownItTOC.style = `max-height: ${innerHeight - 80 > 0 ? innerHeight - 80 : innerHeight}px`
    addTocNumber(tocContent, '');
  })();

  document.addEventListener('scroll', function (e) {
    if (lList.length <= 0) {
      return;
    }
    let scrollTop = document.scrollingElement.scrollTop + 10;
    let dir;

    if (lastTop - scrollTop > 0) {
      dir = 'up';
    } else {
      dir = 'down';
    }

    lastTop = scrollTop;
    if (scrollTop <= 0) {
      if (lastIndex >= 0 && lastIndex < hList.length) {
        lList[lastIndex].classList.remove(activeClass);
      }
      return;
    }

    let current = 0, hasFind = false;
    for (let i = 0; i < hList.length; i++) {
      if (hList[i].offsetTop > scrollTop) {
        current = i;
        hasFind = true;
        break;
      }
    }
    if (!hasFind && scrollTop > lList[lList.length - 1].offsetTop) {
      current = hList.length - 1;
    } else {
      current--;
    }
    if (dir === 'down') {
      if (current > lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex)
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    } else {
      if (current < lastIndex) {
        addActiveClass(current);
        removeActiveClass(lastIndex);
        lastIndex = current;
        removeParentActiveClass();
        lList[current] && addActiveLiElemment(lList[current].parentElement, tocContent);
      }
    }
  });


  window.addEventListener('load', function () {
    showToc();
    document.querySelector('#sidebar').style = 'display: block;';
    tocWrapper.classList.add('toc-active');
    setTimeout(function () {
      if ("createEvent" in document) {
        let evt = document.createEvent("HTMLEvents");
        evt.initEvent("scroll", false, true);
        document.dispatchEvent(evt);
      }
      else {
        document.fireEvent("scroll");
      }
    }, 500)
  })

</script>
            </div>
          
        
      </div>
    </div>
  
</div>
<script>
  const SIDEBAR_TITLE_ACTIVE = 'sidebar-title-active';
  const SIDEBAR_BODY_ACTIVE = 'sidebar-body-active';
  const SLIDE_UP_IN = 'slide-up-in';

  let sidebar = document.querySelector('#sidebar'),
  tocSideBar = document.querySelector('#tocSideBar'),
  metaSideBar = document.querySelector('#metaSideBar'),
  postToc = document.querySelector('#post_toc'),
  postSiteMeta = document.querySelector('#post_side_meta'),
  sidebarTitle = document.querySelector('.sidebar-title'),
  sidebarBody = document.querySelector('#sidebar_body');

  tocSideBar && tocSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  metaSideBar && metaSideBar.addEventListener('click', (e) => {
    toggleSidebar(e);
  });

  function toggleSidebar(e) {
    let currentTitle = document.querySelector("."+SIDEBAR_TITLE_ACTIVE);
    if (currentTitle == e.srcElement) {
      return ;
    }
    let current, showElement, hideElement;
    if (e.srcElement == metaSideBar) {
      showElement = postSiteMeta;
      hideElement = postToc;
    } else if (e.srcElement == tocSideBar){
      showElement = postToc;
      hideElement = postSiteMeta;
    }
    currentTitle.classList.remove(SIDEBAR_TITLE_ACTIVE);
    e.srcElement.classList.add(SIDEBAR_TITLE_ACTIVE);

    window.Velocity(hideElement, 'stop');
    window.Velocity(hideElement, 'transition.slideUpOut', {
      display: 'none',
      duration: 200,
      complete: function () {
        window.Velocity(showElement, 'transition.slideDownIn', {
          duration: 200
        });
      }
    })
    hideElement.classList.remove(SIDEBAR_BODY_ACTIVE);
    showElement.classList.add(SIDEBAR_BODY_ACTIVE);
  }

  postToc && postToc.addEventListener('transitionend', function() {
    this.classList.remove(SLIDE_UP_IN);
  });

  if (sidebarBody) {
    if (sidebarBody.classList.contains('pisces') || sidebarBody.classList.contains('gemini')) {
      let hasFix = false;
      let scrollEl = document.querySelector('.main-continer');
      let limitTop = document.querySelector('#nav_ul').children.length * 42 + 162;
      window.addEventListener('scroll', function(e) {
        if (document.scrollingElement.scrollTop >= limitTop) {
          if (!hasFix) {
            sidebar.classList.add('sidebar-fixed');
            hasFix = true;
          }
        } else {
          if (hasFix) {
            sidebar.classList.remove('sidebar-fixed');
            hasFix = false;
          }
        }
      });
    }
  }
  
</script>
        <div class="section-box box-shadow-wrapper">
          <div class="section bg-color post post-page">
            <section class="post-header">
  <h1 class="post-title">
    <a class="post-title-link" href="/post/BCE4qebR7/">
      Git补坑
    </a>
  </h1>
  <div class="post-meta">
    
    <span class="meta-item pc-show">
      <i class="fa fa-calendar-o"></i>
      <span class="language" data-lan="publish">发布于</span>
      <span class="publish-time" data-t="2019-07-12 19:46:29">2019-07-12</span>
      <span class="post-meta-divider pc-show">|</span>
    </span>
    
    <span class="meta-item">
      <i class="fa fa-folder-o"></i>
      <span class="pc-show language" data-lan="category-in">分类于</span>
      
      
      <a href="/tag/cRVrWpAEg/">
        <span>git</span>
      </a>
      
      
    </span>
    <span class="post-meta-divider">|</span>
    
    <span class="meta-item">
      <i class="fa fa-clock-o"></i>
      <span>20<span class="language" data-lan="minute">分钟</span></span>
    </span>
    <span class="meta-item">
      <span class="post-meta-divider">|</span>
      <i class="fa fa-file-word-o"></i>
      <span>4685<span class="pc-show language" data-lan="words">字数</span></span>
    </span>
    
  </div>
</section>
            <div class="post-body next-md-body" id="post_body">
              <p>这段时间一直忙着写作业和论文，心力交瘁，今天突然发现好久没写博客了（心痛的感觉QAQ），所以来给网站擦擦灰。。</p>
<p>其实以前是很耐心学过Git的，只是没有写博客记录相关内容，现在来补上这个坑 😃</p>
<!-- more -->
<p><span style="color:red;"><strong>值得注意的是：Git只能跟踪文本文件的内容变化，而不能跟踪二进制文件的内容变化（包括Word文档）</strong></span></p>
<h2 id="一-安装git">一、安装Git</h2>
<blockquote>
<h3 id="windows">Windows</h3>
<p>在Windows下，可以在<a href="https://git-scm.com/downloads">官网</a>上下载Windows的安装程序进行安装，安装完成打开Git Bash即可。</p>
<h3 id="mac">Mac</h3>
<p>第一种方法：使用Homebrew进行安装（如果已经安装了<a href="https://brew.sh/index_zh-cn">Homebrew</a>的话），使用命令进行安装：</p>
</blockquote>
<blockquote>
<pre><code class="language-sh">brew install git
</code></pre>
<p>第二种方法：安装Xcode，Xcode集成了Git，但是默认未安装，你可以在Xcode的Preferences-&gt;Download中安装Command Line Tools。</p>
<h3 id="linux">Linux</h3>
<p>Linux不同的发行版有不同的安装方式，可以尝试使用以下方法：</p>
</blockquote>
<blockquote>
<pre><code class="language-sh">sudo apt-get install git
</code></pre>
<p>或者</p>
</blockquote>
<blockquote>
<pre><code class="language-sh">sudo yum install git
</code></pre>
</blockquote>
<p>安装完成后，使用</p>
<pre><code class="language-sh">git config --global user.name &quot;Your Name&quot;
git config --global user.email &quot;user@example.com&quot;
</code></pre>
<p>配置用户名和邮箱。</p>
<h2 id="二-git相关操作">二、Git相关操作</h2>
<h3 id="1创建版本库仓库repository">1.创建版本库(仓库，Repository)</h3>
<pre><code class="language-sh">$ mkdir Test  
$ cd Test
$ git init    // 创建仓库
Initialized empty Git repository in /Volumes/办公/Alan/Test/.git/
</code></pre>
<p>OK, 仓库已经建好，Git会在该目录下生成一个目录.git（.开头为隐藏目录），其用于跟踪管理这个仓库。</p>
<p>如果使用的是某些特殊的shell，当切换到该目录时，可能会出现明显的变化，例如我使用的zsh，当执行git init创建好仓库后，切换到该目录下时（即Test），路径显示变成</p>
<pre><code class="language-sh">Test git:(master) ✗ $
</code></pre>
<h3 id="2添加文件到版本库">2.添加文件到版本库</h3>
<p>添加文件到仓库，让Git跟踪该文件：</p>
<pre><code class="language-sh">$ touch readme.md     // 创建readme.md文件
$ git add readme.md   // 添加readme.md到仓库
$ git add test.php    // 添加test.php到仓库
</code></pre>
<h3 id="3提交文件到版本库">3.提交文件到版本库</h3>
<pre><code class="language-sh">$ git commit -m &quot;add readme.me test.php&quot; // 提交到仓库（-m参数是提交的相关说明，添加提交说明至关重要）
</code></pre>
<p>可多次使用git add添加多个文件，然后使用git commit一次进行提交。每次的git commit都会生成一个新的版本。</p>
<h3 id="4查看提交日志">4.查看提交日志</h3>
<pre><code class="language-sh">$ git log
</code></pre>
<p>显示结果为：</p>
<pre><code class="language-sh">commit bc916412b5b6ca835a21c72a530598db3ae38fb0 (HEAD -&gt; master)
Author: AlanAlbert &lt;1766447919@qq.com&gt;
Date:   Thu Jun 21 09:27:42 2018 +0800

    upload Sort

commit ee45db03f09b212562520be5c1a4e1d853064a2e
Author: AlanAlbert &lt;1766447919@qq.com&gt;
Date:   Thu Jun 21 09:17:41 2018 +0800

    upload readme.md test.php
</code></pre>
<p>git log会根据时间倒序显示每条提交记录，包括提交者、提交时间以及提交说明，也可以给git log加上参数--pretty=oneline让其只显示一行，只包括提交说明：</p>
<pre><code class="language-sh">bc916412b5b6ca835a21c72a530598db3ae38fb0 (HEAD -&gt; master) upload Sort
ee45db03f09b212562520be5c1a4e1d853064a2e upload readme.md test.php
</code></pre>
<p>上面两次都出现的很长一串的字符串是每次提交的id，其通过SHA1计算出来的十六进制数字，保证唯一性。</p>
<h3 id="5重置版本">5.重置版本</h3>
<p>当前版本可以在git log的结果中看到，其用HEAD指向当前版本。上一个版本则为<code>HEAD^</code>，上上个版本为<code>HEAD^^</code>，上5个版本可以表示为<code>HEAD~5</code>。重置到上一个版本为：</p>
<pre><code class="language-sh">$ git reset --hard HEAD^
HEAD is now at ee45db0 upload readme.md test.php
</code></pre>
<p>使用git log --pretty=oneline显示结果：</p>
<pre><code class="language-sh">ee45db03f09b212562520be5c1a4e1d853064a2e (HEAD -&gt; master) upload readme.md test.php
</code></pre>
<p>可见HEAD指向了上一个commit版本。</p>
<blockquote>
<p>git reset命令将HEAD指向另一个commit版本，并将工作目录进行更新。</p>
<p>那么--hard参数是干什么的呢？git reset的参数有三个：--soft、--hard、--mixed，默认为mixed。</p>
<p>① <strong>--soft</strong>: HEAD指向另一个commit版本，而工作区和暂存区不发生变化。即，将HEAD头指针恢复，而add的缓存和工作区的所有东西都不变。</p>
<p>② <strong>--mixed</strong>: HEAD的指向、暂存区都发生变化，工作区不发生变化。即，将HEAD头指针恢复，add的缓存也会丢失，但工作区文件不变。</p>
<p>③ <strong>--hard</strong>: HEAD的指向、暂存区、工作区都发生变化。即，HEAD头指针恢复、add的缓存丢失、工作区的代码修改将恢复。</p>
</blockquote>
<p>在回退到上一个版本后，最新的那个版本不见了，如果又想回到最新的版本怎么办？<br>
办法是有的，只要你知道最新版本的commit id，可以使用：</p>
<pre><code class="language-sh">$ git reset --hard bc91641
HEAD is now at bc91641 upload Sort
</code></pre>
<p>commit id并不需要输入完整，只要能够唯一区分目标版本即可。</p>
<blockquote>
<p>如果实在不记得版本的id，有两种方法可以进行查找，</p>
<p>第一种较简单：使用命令git reflog，第一列显示就是版本id</p>
<p>第二种比较麻烦：在日志文件.git/logs/refs/heads/master中查看，其内容如下：</p>
</blockquote>
<blockquote>
<pre><code class="language-sh">0000000000000000000000000000000000000000 ee45db03f09b212562520be5c1a4e1d853064a2e username &lt;user@example.com&gt; 1529543861 +0800	commit (initial): upload readme.md test.php
ee45db03f09b212562520be5c1a4e1d853064a2e bc916412b5b6ca835a21c72a530598db3ae38fb0 username &lt;user@example.com&gt; 1529544462 +0800	commit: upload Sort
/*结构组成如下：
上一个版本id 当前版本id 用户名 用户邮箱 时间戳 时区(+0800表示正8时区，北京所在时区) 执行的操作: 操作说明
</code></pre>
</blockquote>
<h3 id="6工作区-working-copy和暂存区staging-copy">6.工作区 （working copy）和暂存区（staging copy）</h3>
<p>工作区不用多说，其就是我们可见的目录。<br>
而在工作区下的隐藏文件夹.git下包含一个叫做stage或index的暂存区、第一个分支master以及指向master的指针HEAD，git add就是将文件添加至暂存区，git commit将暂存区的所有内容提交到当前分支，提交后暂存区的内容清空。</p>
<h3 id="7查看状态">7.查看状态</h3>
<p>使用git status可以查看状态：</p>
<pre><code class="language-sh">$ git status
On branch master
Changes to be committed:
  (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage)

  new file:   test1.php
	modified:   test2.php
	
Changes not staged for commit:
  (use &quot;git add &lt;file&gt;...&quot; to update what will be committed)
  (use &quot;git checkout -- &lt;file&gt;...&quot; to discard changes in working directory)

	modified:   test3.php

Untracked files:
  (use &quot;git add &lt;file&gt;...&quot; to include in what will be committed)
  
	test4.php

no changes added to commit (use &quot;git add&quot; and/or &quot;git commit -a&quot;)
</code></pre>
<p>master分支下状态结果显示分三个状态：<br>
① Changes to be committed表示已添加到暂存区但未提交的修改<br>
② Changes not staged for commit表示被修改但未未添加到暂存区的修改，执行git add filename后该修改便会出现在状态① Changes to be committed中，并显示为modified: filename<br>
③ Untracked files表示未跟踪的文件，执行git add filename后该文件便会出现在状态① Changes to be committed中，并显示为new file: filename</p>
<h3 id="8查看差异">8.查看差异</h3>
<p>使用git diff HEAD可以显示最新提交版本和工作区的差异：</p>
<pre><code class="language-sh">$ git diff HEAD
diff --git a/test.php b/test.php
index 94fd6d7..46a8d83 100644
--- a/test.php
+++ b/test.php
@@ -1,7 +1,6 @@
 &lt;?php
 /**
- * add line
+ * test line
  */
    
diff --git a/test2.php b/test2.php
index 10d6ee9..4a3f8ca 100644
--- a/test2.php
+++ b/test2.php
@@ -1,6 +1,6 @@
 &lt;?php
-
+// test.line
</code></pre>
<p>因此，git diff HEAD会显示工作区和最新版本之间所有的差异，如果要检查某一个文件在工作区和最新提交版本之间的差异则使用git diff HEAD -- test.php：</p>
<pre><code class="language-sh">$git diff HEAD -- test.php
diff --git a/test.php b/test.php
index 94fd6d7..46a8d83 100644
--- a/test.php
+++ b/test.php
@@ -1,7 +1,6 @@
 &lt;?php
 /**
- * add line
+ * test line
  */
</code></pre>
<h3 id="9撤销修改">9.撤销修改</h3>
<p>对工作区进行修改后，如果想要放弃这次的修改可以使用：</p>
<pre><code class="language-sh">$ git checkout -- test.php
</code></pre>
<p>该命令会让工作区的文件回到最近一次git commit或git add时的状态。</p>
<h3 id="10删除文件">10.删除文件</h3>
<p>当删除工作区的文件后，使用git status查看状态：</p>
<pre><code class="language-sh">$ git status 
Changes not staged for commit:
  (use &quot;git add/rm &lt;file&gt;...&quot; to update what will be committed)
  (use &quot;git checkout -- &lt;file&gt;...&quot; to discard changes in working directory)

	deleted:    readme.md
	
</code></pre>
<p>可以使用以下命令删除版本库的filename文件：</p>
<pre><code class="language-sh">$ git rm filename
</code></pre>
<p>然后使用git commit将修改提交到版本库。</p>
<h3 id="11添加远程仓库">11.添加远程仓库</h3>
<p>以使用的较多的GitHub为例。<br>
首先，需要在GitHub上为你的账户配置ssh密钥，确保在电脑上可以通过GitHub的验证，可以在命令行或终端使用如下命令进行测试：</p>
<pre><code class="language-sh">$ ssh git@github.com
</code></pre>
<p>若结果显示为：</p>
<pre><code class="language-sh">PTY allocation request failed on channel 0
Hi username! You've successfully authenticated, but GitHub does not provide shell access.
Connection to github.com closed.
</code></pre>
<p>则表示通过GitHub的验证；</p>
<p>然后，使用命令关联远程仓库：</p>
<pre><code class="language-sh">$ git remote add origin git@github.com:username/test.git 
</code></pre>
<p>其中，origin为远程库的名字，然后使用git push将本地库内容推送到远程库：</p>
<pre><code class="language-sh">$ git push -u origin master
</code></pre>
<p>第一次推送时加上-u参数，Git不但会把master分支内容推送给远程新的master分支，还会把本地master分支和远程master分支关联起来。在以后将本地内容推送到远程仓库时，只需要使用以下命令即可：</p>
<pre><code class="language-sh">$ git push origin master
</code></pre>
<p>将远程库的更改合并至当前库：</p>
<pre><code class="language-sh">$ git pull origin master:test // 远程master与test分支合并
$ git pull origin master // 远程master和当前分支合并
</code></pre>
<h3 id="11从远程仓库克隆">11.从远程仓库克隆</h3>
<p>远程仓库的内容克隆到本地：</p>
<pre><code class="language-sh">$ git clone git@github.com:username/test.git
</code></pre>
<p>然后，Git就会下载远程仓库的内容到本地。<br>
Git默认使用的是ssh协议，除此之外还可以使用https等协议，例如：</p>
<pre><code class="language-sh">$ git clone https://github.com/username/test.git
</code></pre>
<h3 id="12分支管理">12.分支管理</h3>
<p>首先了解一下分支是什么？每个分支都是一条timeline(时间线)，前面用到的分支就是master主分支，用户可以在分支上单独操作互不影响。<br>
创建test分支：</p>
<pre><code class="language-sh">$ git branch test
</code></pre>
<p>切换到test分支：</p>
<pre><code class="language-sh">$ git checkout test
Switched to branch 'test'
</code></pre>
<p>以上两步也可以使用一个命令完成：</p>
<pre><code class="language-sh">$ git checkout -b test
</code></pre>
<p>查看所有分支（*号表示当前分支）：</p>
<pre><code class="language-sh">$ git branch
  master
* test
</code></pre>
<p>合并分支：</p>
<pre><code class="language-sh">$ git checkout master
$ git merge test
Updating 8d8593e..4b01548
Fast-forward
 google.md | 0
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 google.md
</code></pre>
<p>删除分支：</p>
<pre><code class="language-sh">$ git branch -d test
Deleted branch test (was cfc8d84).
</code></pre>
<p>为了更好的理解Git的分支，我们做一个小试验：</p>
<blockquote>
<p>① git init创建一个仓库</p>
<p>② 在master分支中新建readme.md，使用git add和git commit提交至仓库</p>
<p>③ 使用git checkout -b test1新建并切换至test1分支，在test1分支中新建并提交test1.md</p>
<p>④ 使用git checkout -b test2新建并切换至test2分支，在test2分支中新建并提交test2.md</p>
<p>⑤ 使用git checkout master切换至master分支，在master分支中新建test.md文件，并提交</p>
<p>⑥ 此时，各分支状况如下图所示：</p>
<figure data-type="image" tabindex="1"><img src="https://media.alan123.xyz/imgs/blogs/git/1.png" alt="分支状况1" loading="lazy"></figure>
<p>⑦ 在master、test1、test2分支中切换时，工作区的文件也会随之变化：切换到master时，工作区有readme.md和test.md；切换至test1分支时，工作区有readme.md和test1.md；切换至test2分支时，工作区有readme.md和test2.md文件</p>
<p>⑧ 切换至master分支，使用git merge test1 test2将test1和test2分支合并至master</p>
<p>⑨ 此时，master分支下的文件包含原来的readme.md、test.md以及加入的test1.md、test2.md，而test1和test2分支未发生变化</p>
<p>⑩ 这时的test1和test2可以用git branch -d test1 test2进行删除</p>
</blockquote>
<p>那么，如果存在两个分支master、test，它们对同一个文件readme.md进行修改（master在文件末尾加入master line，test在文件末尾加入test line），这时，当将test分支合并到master分支时Git会报错。</p>
<pre><code class="language-sh">$ git merge test
Auto-merging readme.md
CONFLICT (content): Merge conflict in readme.md
Automatic merge failed; fix conflicts and then commit the result.
</code></pre>
<p>使用git status查看状态也会提示文件在两个分支都修改了：</p>
<pre><code class="language-sh">On branch master
Your branch is ahead of 'origin/master' by 6 commits.
  (use &quot;git push&quot; to publish your local commits)

You have unmerged paths.
  (fix conflicts and run &quot;git commit&quot;)
  (use &quot;git merge --abort&quot; to abort the merge)

Unmerged paths:
  (use &quot;git add &lt;file&gt;...&quot; to mark resolution)

	both modified:   readme.md

no changes added to commit (use &quot;git add&quot; and/or &quot;git commit -a&quot;)
</code></pre>
<p>此时，需要手动对master主分支下的readme.md文件进行修改，使用vim readme.md打开文件：</p>
<pre><code class="language-sh">  1 &lt;&lt;&lt;&lt;&lt;&lt;&lt; HEAD
  2 master line
  3 =======
  4 test line
  5 &gt;&gt;&gt;&gt;&gt;&gt;&gt; test
</code></pre>
<p>Git将两个分支的readme.md的内容使用&lt;&lt;&lt;&lt;&lt;&lt;&lt;、=======、&gt;&gt;&gt;&gt;&gt;&gt;&gt;区分开来。将内容修改为目标内容，然后git add、git commit即可完成合并。（使用git log --graph可以查看分支合并图）</p>
<h3 id="13分支管理策略">13.分支管理策略</h3>
<p>在合并分支时，如果不指定合并模式，Git会默认使用Fast forward模式，在这个模式下，删除分支信息后，会丢失分支信息。我们可以在合并分支时加上--no-ff参数禁用Fast forward模式，此时Git在合并时会生成一个新的commit：</p>
<pre><code class="language-sh">$ git merge --no-ff -m 'merge test' test
</code></pre>
<p>使用git log --graph --pretty=oneline分别查看禁用Fast forward和不禁用时的区别：</p>
<pre><code class="language-sh"># 不禁用时：
$ git merge test
* 06cf0607846548da37edf16cba68a4b46ba95835 (HEAD -&gt; master) add test.md
* 9ee02e9c78cde794543df93ab508fefb2b7f7667 add readme.md

# 禁用时：
% git merge --no-ff -m 'merge test' test
*   2e6de5d4c6f4c919d63b553615181f51411b3a99 (HEAD -&gt; master) merge test
|\  
| * bbfb8e492523ba516e69813ce7b6b09b7ccd3778 test.md
|/  
* 9ee02e9c78cde794543df93ab508fefb2b7f7667 add readme.md

</code></pre>
<h3 id="14隐藏改变">14.隐藏改变</h3>
<p>当正在为一个Web应用程序进行升级时，突然发现当前版本的程序存在Bug，需要优先修复Bug，此时，升级的工作未完成，尚不能commit，而由于升级修改的文件会影响原来版本，怎么办？</p>
<p>使用git stash命令即可隐藏工作区未提交的工作（前提需要将文件添加到仓库，使得Git能够追踪这些文件）。例如，在当前目录下创建test.md文件并添加至仓库，此时使用</p>
<pre><code class="language-sh">$ git stash
Saved working directory and index state WIP on master: 9ee02e9 add readme.md
</code></pre>
<p>此时，那些未上传的文件在工作区消失了，可以使用以下命令进行查看：</p>
<pre><code class="language-sh">$ git stash list
stash@{0}: WIP on master: 9ee02e9 add readme.md
</code></pre>
<p>Git将相对于最近commit的修改保存至一个类似队列的结构中，可以尝试在使用git stash后再次添加一个文件并使用git stash，然后使用git stash list即可查看到两个stash。</p>
<p>隐藏后如何恢复呢？<br>
① 使用git stash apply，使用后stash的记录和内容不会删除，可以使用git stash drop进行删除；<br>
② 使用git stash pop弹出stash，在恢复的同时，删除stash</p>
<h3 id="15标签管理">15.标签管理</h3>
<p>添加标签：</p>
<pre><code class="language-sh">$ git tag v1.0
</code></pre>
<p>Git默认是为当前分支下的最新commit版本添加标签，如果想为历史提交的版本添加标签，添加上commit id即可：</p>
<pre><code class="language-sh">$ git tag v1.0 commitid
</code></pre>
<p>查看所有标签：</p>
<pre><code class="language-sh">$ git tag
v1.0
</code></pre>
<p>查看标签详细信息：</p>
<pre><code class="language-sh">$ git show v1.0
</code></pre>
<p>删除标签：</p>
<pre><code class="language-sh">$ git tag -d v1.0
</code></pre>
<p>本地标签不会自动推送至远程，可以手动推送至远程库：</p>
<pre><code class="language-sh">$ git push origin v1.0   // 推送标签名v1.0至远程库
$ git push origin --tags // 推送所有标签至远程库
</code></pre>
<p>删除远程库标签：</p>
<pre><code class="language-sh">$ git push origin :refs/tags/v1.0  // 删除标签v1.0
</code></pre>
<h3 id="16多人协作的工作流程">16.多人协作的工作流程</h3>
<p>多人协作的工作模式通常是这样：</p>
<ol>
<li>
<p>首先，可以试图用git push origin <branch-name>推送自己的修改；</p>
</li>
<li>
<p>如果推送失败，则因为远程分支比你的本地更新，需要先用git pull试图合并；</p>
</li>
<li>
<p>如果合并有冲突，则解决冲突，并在本地提交；</p>
</li>
<li>
<p>没有冲突或者解决掉冲突后，再用git push origin <branch-name>推送就能成功！</p>
</li>
</ol>
<p>如果git pull提示no tracking information，则说明本地分支和远程分支的链接关系没有创建，用命令git branch --set-upstream-to <branch-name> origin/<branch-name>。</p>
<p>这就是多人协作的工作模式，一旦熟悉了，就非常简单。</p>
<h2 id="三-总结">三、总结</h2>
<p>善用Git的--help可以帮助更好的使用命令，例如：</p>
<pre><code class="language-sh">$ git --help
$ git pull --help
</code></pre>
<table>
<thead>
<tr>
<th>命令</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>git config —global user.name “&lt; username &gt;&quot;</td>
<td>配置用户名</td>
</tr>
<tr>
<td>git config —global user.email “&lt; user@example.com &gt;&quot;</td>
<td>配置邮箱</td>
</tr>
<tr>
<td>git init</td>
<td>创建版本库</td>
</tr>
<tr>
<td>git add &lt; file &gt;</td>
<td>添加文件到版本库（Git追踪该文件）</td>
</tr>
<tr>
<td>git commit -m “&lt; commit message &gt;&quot;</td>
<td>将改动提交到版本库</td>
</tr>
<tr>
<td>git log [--graph --pretty=oneline ...]</td>
<td>查看版本库日志信息</td>
</tr>
<tr>
<td>git reflog</td>
<td>查看所有分支的所有操作日志</td>
</tr>
<tr>
<td>git reset --hard &lt; version &gt;</td>
<td>重置版本,HEAD^,HEAD~5,commit id</td>
</tr>
<tr>
<td>git status</td>
<td>查看状态</td>
</tr>
<tr>
<td>git diff &lt; version &gt;</td>
<td>查看版本和当前工作区差异</td>
</tr>
<tr>
<td>git checkout — &lt; file &gt;</td>
<td>恢复至最近commit或add时的状态</td>
</tr>
<tr>
<td>git rm &lt; file &gt;</td>
<td>从版本库删除文件</td>
</tr>
<tr>
<td>git remote add &lt; 远程库名 &gt; &lt; address &gt;</td>
<td>关联远程仓库（远程库名、地址）</td>
</tr>
<tr>
<td>git push [-u] &lt; 远程库名 &gt; &lt; branch &gt;</td>
<td>本地库内容推送至远程，第一次加-u（，分支）</td>
</tr>
<tr>
<td>git pull origin &lt; 远程分支名 &gt;:&lt; 本地分支名 &gt;</td>
<td>将远程库的更改合并至当前库</td>
</tr>
<tr>
<td>git clone &lt; address &gt;</td>
<td>远程仓库的内容克隆到本地</td>
</tr>
<tr>
<td>git branch &lt; branch &gt;</td>
<td>添加分支</td>
</tr>
<tr>
<td>git branch -d &lt; branch &gt;</td>
<td>删除分支</td>
</tr>
<tr>
<td>git branch</td>
<td>显示所有分支</td>
</tr>
<tr>
<td>git checkout &lt; branch &gt;</td>
<td>切换分支</td>
</tr>
<tr>
<td>git checkout -b &lt; branch &gt;</td>
<td>新建并切换分支</td>
</tr>
<tr>
<td>git merge &lt; branch &gt;</td>
<td>合并分支</td>
</tr>
<tr>
<td>git merge --no-ff -m “&lt; commit message &gt;” &lt; branch &gt;</td>
<td>禁用Fast forward模式合并分支</td>
</tr>
<tr>
<td>git stash</td>
<td>隐藏已跟踪未提交的工作区内容</td>
</tr>
<tr>
<td>git stash list</td>
<td>显示stash</td>
</tr>
<tr>
<td>git stash apply</td>
<td>恢复隐藏内容，但不删除</td>
</tr>
<tr>
<td>git stash drop</td>
<td>删除stash记录</td>
</tr>
<tr>
<td>git stash pop</td>
<td>恢复隐藏内容，并删除</td>
</tr>
<tr>
<td>git tag &lt; tag name &gt; [&lt; commit id &gt;]</td>
<td>添加标签</td>
</tr>
<tr>
<td>git tag</td>
<td>显示所有标签</td>
</tr>
<tr>
<td>git show &lt; tag name &gt;</td>
<td>显示tag详细信息</td>
</tr>
<tr>
<td>git tag -d &lt; tag name &gt;</td>
<td>删除标签</td>
</tr>
<tr>
<td>git push &lt; 远程库名 &gt; &lt; tag name &gt;</td>
<td>推送标签至远程库</td>
</tr>
<tr>
<td>git push &lt; 远程库名 &gt; --tags</td>
<td>推送所有标签至远程库</td>
</tr>
<tr>
<td>git push &lt; 远程库名 &gt; :refs/tags/&lt; tag name &gt;</td>
<td>删除远程库标签</td>
</tr>
</tbody>
</table>
<h2 id="四-实际使用">四、实际使用</h2>
<h3 id="1-在github上修改他人项目的代码">1、在GitHub上，修改他人项目的代码</h3>
<p>① 在GitHub上，将项目从他人仓库fork到自己仓库；</p>
<p>② 使用git clone将自己仓库的项目clone到本地；</p>
<p>③ 修改完代码后，将修改push到自己远程仓库；</p>
<p>④ 在GitHub上，创建Pull Request，等待原仓库管理员的审核；</p>
<h3 id="2-pull-request被合并后">2、Pull Request被合并后</h3>
<p>最近在GitHub上修改别人的代码，遇到一个问题：我在第二次提交Pull Request时，将第一次已合并的Pull Request再次提交了上去。（毕竟第一次嘛😂</p>
<p>需要注意的是，在我们的Pull Request被合并时，我们需要做的工作有：</p>
<blockquote>
<p>① 给fork配置远程库：</p>
<p>使用<code>git remote -v</code>可以查看远程仓库状态。如果结果中没有原仓库的配置，可以使用<code>git remote add 自定义名 原仓库地址</code>进行配置，例如：<code>git remote add nickname https://github.com/username/repostory.git</code></p>
<p>② 使用<code>git fetch nickname</code>从原仓库fetch分支和提交点到本地，并存储到本地分支nickname/master</p>
<p>③ 切换到master分支：<code>git checkout master</code></p>
<p>④ 将nickname/master分支合并到本地master：<code>git merge nickname/master</code></p>
<p>⑤ 更新到GitHub的fork上：<code>git push origin master</code></p>
<p><strong>（原仓库即上游仓库）</strong></p>
</blockquote>

            </div>
            
            
              <div class="post-footer">
  <ul class="post-copyright">
    <li class="post-copyright-author">
      <strong class="language" data-lan="author">本文作者：</strong>
      anhoder
    </li>
    <li class="post-copyright-link">
      <strong class="language" data-lan="link">本文链接：</strong>
      <a href="/post/BCE4qebR7/" title="Git补坑">/post/BCE4qebR7/</a>
    </li>
    <li class="post-copyright-license">
      <strong class="language" data-lan="copyright">版权声明： </strong>
      本博客所有文章除特别声明外，均采用<a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i> BY-NC-SA</a> 许可协议。转载请注明出处！
    </li>
  </ul>
  <div class="tags">
    
      <a href="/tag/cRVrWpAEg/"># git</a>
    
  </div>
  <div class="nav">
    <div class="nav-prev">
      
        <i class="fa fa-chevron-left"></i>
        <a class="nav-pc-next" title="PHP扩展之全局变量的使用" href="/post/ek0IMhO66/">PHP扩展之全局变量的使用</a class="nav-pc-next">
        <a class="nav-mobile-prev" title="PHP扩展之全局变量的使用" href="/post/ek0IMhO66/">上一篇</a>
      
    </div>
    <div class="nav-next">
      
        <a class="nav-pc-next" title="Git Flow与git-flow的介绍" href="/post/YZYCy5Hq6/">Git Flow与git-flow的介绍</a>
        <a class="nav-mobile-next" title="Git Flow与git-flow的介绍" href="/post/YZYCy5Hq6/">下一篇</a>
        <i class="fa fa-chevron-right"></i>
      
    </div>
  </div>
</div>
            
            
  
    
      <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

<div id="gitalk-container"></div>

<script>
  var gitalk = new Gitalk({
    clientID: '8254f894b17fffeef6e2',
    clientSecret: 'aa345603999774a44649ad73ef7fe72ee45a021b',
    repo: 'personal-blog-comments',
    owner: 'anhoder',
    admin: ['anhoder'],
    id: (location.pathname).substring(0, 49),      // Ensure uniqueness and length less than 50
    distractionFreeMode: false  // Facebook-like distraction free mode
  })
  gitalk.render('gitalk-container')
</script>
    
    
  

          </div>
        </div>
      </div>
    </div>
    <div class="footer-box">
  <footer class="footer">
    <div class="poweredby">
      © Authored by <a href="https://github.com/anhoder">anhoder</a> since 2019.
    </div>
    <div class="copyright">
      Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a> | Theme By <a
        href="https://github.com/hsxyhao/gridea-theme-next" target="_blank">HsxyHao</a>
    </div>
  </footer>
  
  
  <div class="pisces back-to-top" id="back_to_top">
    <i class="fa fa-arrow-up"></i>
    
    <span class="scrollpercent">
      <span id="back_to_top_text">0</span>%
    </span>
    
  </div>
  
  
  
<link rel="stylesheet" href="/media/live2d/css/live2d.css" />
<div class="box-scale">
  <div id="landlord" style="left: 100%px;bottom: 100%px;"
    data-key="">
    <canvas id="live2d" width="500" height="560" class="live2d"></canvas>
    
  </div>
</div>
<div id="open_live2d">召唤看板娘</div>
<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
  var message_Path = 'https://cdn.jsdelivr.net/gh/anhoder/source-for-blog@master/';
  let landlord = document.querySelector('#landlord');
  var apiKey = landlord.dataset.key;
</script>
<script type="text/javascript" src="/media/live2d/js/live2d.js"></script>
<script>
	var home_Path = document.location.protocol + '//' + window.document.location.hostname + ":" + window.document.location.port + '/';
	var userAgent = window.navigator.userAgent.toLowerCase();
	var norunAI = ["android", "iphone", "ipod", "ipad", "windows phone", "mqqbrowser", "msie", "trident/7.0"];
	var norunFlag = false;

	for (var i = 0; i < norunAI.length; i++) {
		if (userAgent.indexOf(norunAI[i]) > -1) {
			norunFlag = true;
			break;
		}
	}

	if (!window.WebGLRenderingContext) {
		norunFlag = true;
	}

	if (!norunFlag) {
		var hitFlag = false;
		var AIFadeFlag = false;
		var liveTlakTimer = null;
		var sleepTimer_ = null;
		var AITalkFlag = false;
		var talkNum = 0;
		(function () {
			function renderTip(template, context) {
				var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;
				return template.replace(tokenReg, function (word, slash1, token, slash2) {
					if (slash1 || slash2) {
						return word.replace('\\', '');
					}
					var variables = token.replace(/\s/g, '').split('.');
					var currentObject = context;
					var i, length, variable;
					for (i = 0, length = variables.length; i < length; ++i) {
						variable = variables[i];
						currentObject = currentObject[variable];
						if (currentObject === undefined || currentObject === null) return '';
					}
					return currentObject;
				});
			}

			String.prototype.renderTip = function (context) {
				return renderTip(this, context);
			};

			var re = /x/;
			re.toString = function () {
				showMessage('哈哈，你打开了控制台，是想要看看我的秘密吗？', 5000);
				return '';
			};

			$(document).on('copy', function () {
				showMessage('你都复制了些什么呀，转载要记得加上出处哦~~', 5000);
			});

			function initTips() {
				$.ajax({
					cache: true,
					url: message_Path + 'message.json',
					dataType: "json",
					success: function (result) {
						$.each(result.mouseover, function (index, tips) {
							$(tips.selector).mouseover(function () {
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
								talkValTimer();
								clearInterval(liveTlakTimer);
								liveTlakTimer = null;
							});
							$(tips.selector).mouseout(function () {
								showHitokoto();
								if (liveTlakTimer == null) {
									liveTlakTimer = window.setInterval(function () {
										showHitokoto();
									}, 15000);
								};
							});
						});
						$.each(result.click, function (index, tips) {
							$(tips.selector).click(function () {
								if (hitFlag) {
									return false
								}
								hitFlag = true;
								setTimeout(function () {
									hitFlag = false;
								}, 8000);
								var text = tips.text;
								if (Array.isArray(tips.text)) text = tips.text[Math.floor(Math.random() * tips.text.length + 1) - 1];
								text = text.renderTip({ text: $(this).text() });
								showMessage(text, 3000);
							});
							clearInterval(liveTlakTimer);
							liveTlakTimer = null;
							if (liveTlakTimer == null) {
								liveTlakTimer = window.setInterval(function () {
									showHitokoto();
								}, 15000);
							};
						});
					}
				});
			}
			initTips();

			var text;
			if (document.referrer !== '') {
				var referrer = document.createElement('a');
				referrer.href = document.referrer;
				text = '嗨！来自 <span style="color:#0099cc;">' + referrer.hostname + '</span> 的朋友！';
				var domain = referrer.hostname.split('.')[1];
				if (domain == 'baidu') {
					text = '嗨！ 来自 百度搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'so') {
					text = '嗨！ 来自 360搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				} else if (domain == 'google') {
					text = '嗨！ 来自 谷歌搜索 的朋友！<br>欢迎访问<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			} else {
				if (window.location.href == home_Path) { //主页URL判断，需要斜杠结尾
					var now = (new Date()).getHours();
					if (now > 23 || now <= 5) {
						text = '你是夜猫子呀？这么晚还不睡觉，明天起的来嘛？';
					} else if (now > 5 && now <= 7) {
						text = '早上好！一日之计在于晨，美好的一天就要开始了！';
					} else if (now > 7 && now <= 11) {
						text = '上午好！工作顺利嘛，不要久坐，多起来走动走动哦！';
					} else if (now > 11 && now <= 14) {
						text = '中午了，工作了一个上午，现在是午餐时间！';
					} else if (now > 14 && now <= 17) {
						text = '午后很容易犯困呢，今天的运动目标完成了吗？';
					} else if (now > 17 && now <= 19) {
						text = '傍晚了！窗外夕阳的景色很美丽呢，最美不过夕阳红~~';
					} else if (now > 19 && now <= 21) {
						text = '晚上好，今天过得怎么样？';
					} else if (now > 21 && now <= 23) {
						text = '已经这么晚了呀，早点休息吧，晚安~~';
					} else {
						text = '嗨~ 快来逗我玩吧！';
					}
				} else {
					text = '欢迎阅读<span style="color:#0099cc;">「 ' + document.title.split(' - ')[0] + ' 」</span>';
				}
			}
			showMessage(text, 12000);
		})();

		liveTlakTimer = setInterval(function () {
			showHitokoto();
		}, 15000);

		function showHitokoto() {
			if (sessionStorage.getItem("Sleepy") !== "1") {
				if (!AITalkFlag) {
					$.getJSON('https://v1.hitokoto.cn/', function (result) {
						talkValTimer();
						showMessage(result.hitokoto, 0);
					});
				}
			} else {
				hideMessage(0);
				if (sleepTimer_ == null) {
					sleepTimer_ = setInterval(function () {
						checkSleep();
					}, 200);
				}
			}
		}

		function checkSleep() {
			var sleepStatu = sessionStorage.getItem("Sleepy");
			if (sleepStatu !== '1') {
				talkValTimer();
				showMessage('你回来啦~', 0);
				clearInterval(sleepTimer_);
				sleepTimer_ = null;
			}
		}

		function showMessage(text, timeout) {
			if (Array.isArray(text)) text = text[Math.floor(Math.random() * text.length + 1) - 1];
			$('.message').stop();
			$('.message').html(text);
			$('.message').fadeTo(200, 1);
			//if (timeout === null) timeout = 5000;
			//hideMessage(timeout);
		}
		function talkValTimer() {
			$('#live_talk').val('1');
		}

		function hideMessage(timeout) {
			//$('.message').stop().css('opacity',1);
			if (timeout === null) timeout = 5000;
			$('.message').delay(timeout).fadeTo(200, 0);
		}

		function initLive2d() {
			$('#hideButton').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "0");
					$('#landlord').fadeOut(200);
					$('#open_live2d').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#open_live2d').on('click', function () {
				if (AIFadeFlag) {
					return false;
				} else {
					AIFadeFlag = true;
					localStorage.setItem("live2dhidden", "1");
					$('#open_live2d').fadeOut(200);
					$('#landlord').delay(200).fadeIn(200);
					setTimeout(function () {
						AIFadeFlag = false;
					}, 300);
				}
			});
			$('#youduButton').on('click', function () {
				if ($('#youduButton').hasClass('doudong')) {
					var typeIs = $('#youduButton').attr('data-type');
					$('#youduButton').removeClass('doudong');
					$('body').removeClass(typeIs);
					$('#youduButton').attr('data-type', '');
				} else {
					var duType = $('#duType').val();
					var duArr = duType.split(",");
					var dataType = duArr[Math.floor(Math.random() * duArr.length)];

					$('#youduButton').addClass('doudong');
					$('#youduButton').attr('data-type', dataType);
					$('body').addClass(dataType);
				}
			});
			if (apiKey) {
				$('#showInfoBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "0") {
						return
					} else {
						$('#live_statu_val').val("0");
						$('.live_talk_input_body').fadeOut(500);
						AITalkFlag = false;
						showHitokoto();
						$('#showTalkBtn').show();
						$('#showInfoBtn').hide();
					}
				});
				$('#showTalkBtn').on('click', function () {
					var live_statu = $('#live_statu_val').val();
					if (live_statu == "1") {
						return
					} else {
						$('#live_statu_val').val("1");
						$('.live_talk_input_body').fadeIn(500);
						AITalkFlag = true;
						$('#showTalkBtn').hide();
						$('#showInfoBtn').show();

					}
				});
				$('#talk_send').on('click', function () {
					var info_ = $('#AIuserText').val();
					var userid_ = $('#AIuserName').val();
					if (info_ == "") {
						showMessage('写点什么吧！', 0);
						return;
					}
					if (userid_ == "") {
						showMessage('聊之前请告诉我你的名字吧！', 0);
						return;
					}
					showMessage('思考中~', 0);
					let protocol = window.location.protocol.indexOf("s") > 0 ? "https" : "http";
					$.ajax({
						type: "get",
						url: `${protocol}://www.tuling123.com/openapi/api?key=${apiKey}&info=${info_}`,
						dataType: "json",
						success: function (res) {
							talkValTimer();
							showMessage(res.text, 0);
							$('#AIuserText').val("");
							sessionStorage.setItem("live2duser", userid_);
						},
						error: function (e) {
							talkValTimer();
							showMessage('似乎有什么错误，请和站长联系！', 0);
						}
					});
				});
			} else {
				$('#showInfoBtn').hide();
				$('#showTalkBtn').hide();
			}
			//获取音乐信息初始化
			var bgmListInfo = $('input[name=live2dBGM]');
			if (bgmListInfo.length == 0) {
				$('#musicButton').hide();
			} else {
				var bgmPlayNow = parseInt($('#live2d_bgm').attr('data-bgm'));
				var bgmPlayTime = 0;
				var live2dBGM_Num = sessionStorage.getItem("live2dBGM_Num");
				var live2dBGM_PlayTime = sessionStorage.getItem("live2dBGM_PlayTime");
				if (live2dBGM_Num) {
					if (live2dBGM_Num <= $('input[name=live2dBGM]').length - 1) {
						bgmPlayNow = parseInt(live2dBGM_Num);
					}
				}
				if (live2dBGM_PlayTime) {
					bgmPlayTime = parseInt(live2dBGM_PlayTime);
				}
				var live2dBGMSrc = bgmListInfo.eq(bgmPlayNow).val();
				$('#live2d_bgm').attr('data-bgm', bgmPlayNow);
				$('#live2d_bgm').attr('src', live2dBGMSrc);
				$('#live2d_bgm')[0].currentTime = bgmPlayTime;
				$('#live2d_bgm')[0].volume = 0.5;
				var live2dBGM_IsPlay = sessionStorage.getItem("live2dBGM_IsPlay");
				var live2dBGM_WindowClose = sessionStorage.getItem("live2dBGM_WindowClose");
				if (live2dBGM_IsPlay == '0' && live2dBGM_WindowClose == '0') {
					$('#live2d_bgm')[0].play();
					$('#musicButton').addClass('play');
				}
				sessionStorage.setItem("live2dBGM_WindowClose", '1');
				$('#musicButton').on('click', function () {
					if ($('#musicButton').hasClass('play')) {
						$('#live2d_bgm')[0].pause();
						$('#musicButton').removeClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '1');
					} else {
						$('#live2d_bgm')[0].play();
						$('#musicButton').addClass('play');
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				});
				window.onbeforeunload = function () {
					sessionStorage.setItem("live2dBGM_WindowClose", '0');
					if ($('#musicButton').hasClass('play')) {
						sessionStorage.setItem("live2dBGM_IsPlay", '0');
					}
				}
				document.getElementById('live2d_bgm').addEventListener("timeupdate", function () {
					var live2dBgmPlayTimeNow = document.getElementById('live2d_bgm').currentTime;
					sessionStorage.setItem("live2dBGM_PlayTime", live2dBgmPlayTimeNow);
				});
				document.getElementById('live2d_bgm').addEventListener("ended", function () {
					var listNow = parseInt($('#live2d_bgm').attr('data-bgm'));
					listNow++;
					if (listNow > $('input[name=live2dBGM]').length - 1) {
						listNow = 0;
					}
					var listNewSrc = $('input[name=live2dBGM]').eq(listNow).val();
					sessionStorage.setItem("live2dBGM_Num", listNow);
					$('#live2d_bgm').attr('src', listNewSrc);
					$('#live2d_bgm')[0].play();
					$('#live2d_bgm').attr('data-bgm', listNow);
				});
				document.getElementById('live2d_bgm').addEventListener("error", function () {
					$('#live2d_bgm')[0].pause();
					$('#musicButton').removeClass('play');
					showMessage('音乐似乎加载不出来了呢！', 0);
				});
			}
			//获取用户名
			var live2dUser = sessionStorage.getItem("live2duser");
			if (live2dUser !== null) {
				$('#AIuserName').val(live2dUser);
			}
			//获取位置
			var landL = sessionStorage.getItem("historywidth");
			var landB = sessionStorage.getItem("historyheight");
			if (landL == null || landB == null) {
				landL = '5px'
				landB = '0px'
			}
			$('#landlord').css('left', landL + 'px');
			$('#landlord').css('bottom', landB + 'px');
			//移动
			function getEvent() {
				return window.event || arguments.callee.caller.arguments[0];
			}
			var smcc = document.getElementById("landlord");
			var moveX = 0;
			var moveY = 0;
			var moveBottom = 0;
			var moveLeft = 0;
			var moveable = false;
			var docMouseMoveEvent = document.onmousemove;
			var docMouseUpEvent = document.onmouseup;
			smcc.onmousedown = function () {
				var ent = getEvent();
				moveable = true;
				moveX = ent.clientX;
				moveY = ent.clientY;
				var obj = smcc;
				moveBottom = parseInt(obj.style.bottom);
				moveLeft = parseInt(obj.style.left);
				if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
					window.getSelection().removeAllRanges();
				}
				document.onmousemove = function () {
					if (moveable) {
						var ent = getEvent();
						var x = moveLeft + ent.clientX - moveX;
						var y = moveBottom + (moveY - ent.clientY);
						obj.style.left = x + "px";
						obj.style.bottom = y + "px";
					}
				};
				document.onmouseup = function () {
					if (moveable) {
						var historywidth = obj.style.left;
						var historyheight = obj.style.bottom;
						historywidth = historywidth.replace('px', '');
						historyheight = historyheight.replace('px', '');
						sessionStorage.setItem("historywidth", historywidth);
						sessionStorage.setItem("historyheight", historyheight);
						document.onmousemove = docMouseMoveEvent;
						document.onmouseup = docMouseUpEvent;
						moveable = false;
						moveX = 0;
						moveY = 0;
						moveBottom = 0;
						moveLeft = 0;
					}
				};
			};
		}
		$(document).ready(function () {
			var AIimgSrc = [];
			let chooseLive2d = 'plt'
			if (chooseLive2d === 'histoire') {
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_00.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_01.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_02.png");
				AIimgSrc.push(message_Path + "model/histoire/histoire.1024/texture_03.png");
			} else if (chooseLive2d === 'rem') {
				AIimgSrc.push(message_Path + "model/rem/remu2048/texture_00.png");
			} else if (chooseLive2d === 'aoba') {
				AIimgSrc.push(message_Path + "model/aoba/textures/texture_00.png");
			} else if (chooseLive2d === 'hijiki') {
				AIimgSrc.push(message_Path + "model/hijiki/moc/hijiki.2048/texture_00.png");
			} else if (chooseLive2d === 'tororo') {
				AIimgSrc.push(message_Path + "model/tororo/moc/tororo.2048/texture_00.png");
			} else if (chooseLive2d === 'plt') {
				AIimgSrc.push(message_Path + "model/plt/moc/plt.2048/texture_00.png");
			}
			var images = [];
			var imgLength = AIimgSrc.length;
			var loadingNum = 0;
			for (var i = 0; i < imgLength; i++) {
				images[i] = new Image();
				images[i].src = AIimgSrc[i];
				images[i].onload = function () {
					loadingNum++;
					if (loadingNum === imgLength) {
						var live2dhidden = localStorage.getItem("live2dhidden");
						if (live2dhidden === "0") {
							setTimeout(function () {
								$('#open_live2d').fadeIn(200);
							}, 1300);
						} else {
							setTimeout(function () {
								$('#landlord').fadeIn(200);
							}, 1300);
						}
						let model = '';
						if (chooseLive2d === 'histoire') {
							model = message_Path + "model/histoire/model.json";
						} else if (chooseLive2d === 'rem') {
							model = message_Path + "model/rem/model.json";
						} else if (chooseLive2d === 'aoba') {
							model = message_Path + "model/aoba/model.json";
						} else if (chooseLive2d === 'hijiki') {
							model = message_Path + "model/hijiki/hijiki.model.json";
						} else if (chooseLive2d === 'tororo') {
							model = message_Path + "model/tororo/tororo.model.json";
						} else if (chooseLive2d === 'plt') {
							model = message_Path + "model/plt/model.json?v=1617466520";
						}
						setTimeout(function () {
							loadlive2d("live2d", model);
						}, 1000);
						initLive2d();
						images = null;
					}
				}
			}
		});
	}
</script>
  
  
</div>
<script>

  let sideBarOpen = 'sidebar-open';
  let body = document.body;
  let back2Top = document.querySelector('#back_to_top'),
    back2TopText = document.querySelector('#back_to_top_text'),
    drawerBox = document.querySelector('#drawer_box'),
    rightSideBar = document.querySelector('.sidebar'),
    viewport = document.querySelector('body');

  function scrollAnimation(currentY, targetY) {

    let needScrollTop = targetY - currentY
    let _currentY = currentY
    setTimeout(() => {
      const dist = Math.ceil(needScrollTop / 10)
      _currentY += dist
      window.scrollTo(_currentY, currentY)
      if (needScrollTop > 10 || needScrollTop < -10) {
        scrollAnimation(_currentY, targetY)
      } else {
        window.scrollTo(_currentY, targetY)
      }
    }, 1)
  }

  back2Top.addEventListener("click", function (e) {
    scrollAnimation(document.scrollingElement.scrollTop, 0);
    e.stopPropagation();
    return false;
  });

  window.addEventListener('scroll', function (e) {
    let percent = document.scrollingElement.scrollTop / (document.scrollingElement.scrollHeight - document.scrollingElement.clientHeight) * 100;
    if (percent > 1 && !back2Top.classList.contains('back-top-active')) {
      back2Top.classList.add('back-top-active');
    }
    if (percent == 0) {
      back2Top.classList.remove('back-top-active');
    }
    if (back2TopText) {
      back2TopText.textContent = Math.floor(percent);
    }
  });


  let hasCacu = false;
  window.onresize = function () {
    calcuHeight();
  }

  function calcuHeight() {
    // 动态调整站点概览高度
    if (!hasCacu && back2Top.classList.contains('pisces') || back2Top.classList.contains('gemini')) {
      let sideBar = document.querySelector('.sidebar');
      let navUl = document.querySelector('#site_nav');
      sideBar.style = 'margin-top:' + (navUl.offsetHeight + navUl.offsetTop + 15) + 'px;';
      hasCacu = true;
    }
  }
  calcuHeight();

  let open = false, MOTION_TIME = 300, RIGHT_MOVE_DIS = '320px';

  if (drawerBox) {
    let rightMotions = document.querySelectorAll('.right-motion');
    let right = drawerBox.classList.contains('right');

    let transitionDir = right ? "transition.slideRightIn" : "transition.slideLeftIn";

    let openProp, closeProp;
    if (right) {
      openProp = {
        paddingRight: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingRight: '0px'
      };
    } else {
      openProp = {
        paddingLeft: RIGHT_MOVE_DIS
      };
      closeProp = {
        paddingLeft: '0px'
      };
    }

    drawerBox.onclick = function () {
      open = !open;
      window.Velocity(rightSideBar, 'stop');
      window.Velocity(viewport, 'stop');
      window.Velocity(rightMotions, 'stop');
      if (open) {
        window.Velocity(rightSideBar, {
          width: RIGHT_MOVE_DIS
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, transitionDir, {});
          }
        })
        window.Velocity(viewport, openProp, {
          duration: MOTION_TIME
        });
      } else {
        window.Velocity(rightSideBar, {
          width: '0px'
        }, {
          duration: MOTION_TIME,
          begin: function () {
            window.Velocity(rightMotions, {
              opacity: 0
            });
          }
        })
        window.Velocity(viewport, closeProp, {
          duration: MOTION_TIME
        });
      }
      for (let i = 0; i < drawerBox.children.length; i++) {
        drawerBox.children[i].classList.toggle('muse-line');
      }
      drawerBox.classList.toggle(sideBarOpen);
    }
  }

  // 链接跳转
  let newWindow = 'false'
  if (newWindow === 'true') {
    let links = document.querySelectorAll('.post-body a')
    links.forEach(item => {
      if (!item.classList.contains('btn')) {
        item.setAttribute("target", "_blank");
      }
    })
  }

  let faSearch = document.querySelector('#fa_search');
  faSearch && faSearch.addEventListener('click', function () {
    document.querySelector('#search_mask').style = ''
  })

  // 代码高亮
  hljs.initHighlightingOnLoad();
  
  // 离开当前页title变化
  var leaveTitle = "";
  if (leaveTitle) {
    document.addEventListener('visibilitychange', function () {
      if (document.visibilityState == 'hidden') {
        normal_title = document.title;
        document.title = leaveTitle;
      } else {
        document.title = normal_title;
      }
    });
  }

</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js"></script>

<script>
  let images = document.querySelectorAll('.section img');
  console.log(images);
  images.forEach(image => {
    if (image.classList.contains('no-fancybox')) {
      return;
    }

    var parent = image.parentElement;
    var next = image.nextElementSibling;
    parent.removeChild(image);
    var aelem = document.createElement('a');
    aelem.href = image.src;
    aelem.dataset['fancybox'] = 'images';
    aelem.dataset['rel'] = 'fancybox-button';
    aelem.classList.add('fancybox');
    aelem.appendChild(image);
    parent.insertBefore(aelem, next);
  })
</script>
    <div class="reward-mask" style="display: none;">
  <div class="reward-relative">
    <span class="close" aria-hidden="true">x</span>
    <div class="reward-body">
      <h2>感谢您的支持，我会继续努力的!</h2>
      <div class="reward-img-box">
        <div style="position: relative; width: 140px; height: 140px;">
          
          
          
        </div>
      </div>
      <p class="reward-word">扫码打赏，你说多少就多少</p>
      <p class="reward-tip">打开微信扫一扫，即可进行扫码打赏哦</p>
    </div>
    <div class="bottom">
      
      
    </div>
  </div>
</div>
<style>
  .reward-mask {
    position: fixed;
    z-index: 99999;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #00000054;
  }

  .reward-relative {
    position: relative;
    width: 480px;
    text-align: center;
    margin: 0 auto;
    border-radius: 5px;
    background-color: #fff;
    top: 50%;
    margin-top: -205px;
  }

  .reward-relative .close {
    position: absolute;
    right: 10px;
    font-weight: normal;
    font-size: 16px;
    color: #929292;
  }

  .reward-body {
    padding: 40px 20px 20px;
  }

  .bottom {
    display: flex;
  }

  .reward-btn {
    text-align: center;
  }

  .reward-btn-text {
    display: inline-block;
    cursor: pointer;
    width: 60px;
    height: 60px;
    line-height: 60px;
    border-radius: 50%;
    background-color: #ff9734;
    color: #FFF;
    margin-top: 20px;
  }

  .pay-text {
    margin-top: 10px;
    padding: 10px;
    flex: 1;
    transition: all .2s linear;
  }

  .pay-text:hover {
    background-color: #a5a5a536;
  }

  .reward-body h2 {
    padding-top: 10px;
    text-align: center;
    color: #a3a3a3;
    font-size: 16px;
    font-weight: normal;
    margin: 0 0 20px;
  }

  .reward-body h2:after,
  .reward-body h2:before {
    font-family: Arial, Helvetica, sans-serif;
    background: 0 0;
    width: 0;
    height: 0;
    font-style: normal;
    color: #eee;
    font-size: 80px;
    position: absolute;
    top: 20px;
  }

  .reward-body h2:before {
    content: '\201c';
    left: 50px;
  }

  .reward-body h2:after {
    content: '\201d';
    right: 80px;
  }

  .reward-img-box {
    display: inline-block;
    padding: 10px;
    border: 6px solid #ea5f00;
    margin: 0 auto;
    border-radius: 3px;
    position: relative;
  }

  .reward-img {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
  }

  @media (max-width: 767px) {
    .reward-relative {
      height: 100%;
      top: 0px;
      margin-top: 0;
      width: auto;
    }

    .reward-relative .bottom {
      flex-direction: column;
    }

    .reward-relative .pay-text {
      width: 80%;
      margin: 5px auto;
      border: 1px solid silver;
      padding: 6px;
      border-radius: 4px;
    }

    .reward-body h2:after {
      right: 40px;
    }

    .reward-body h2:after,
    .reward-body h2:before {
      font-size: 60px;
    }

    .reward-body h2:before {
      left: 20px;
    }
  }
</style>
<script>
  !function () {
    var mask = document.querySelector('.reward-mask');
    let close = document.querySelector('.reward-relative .close');
    let rewardBtn = document.querySelector('.reward-btn');

    let zfb = document.querySelector('#zfb'),
      wx = document.querySelector('#wx'),
      zfbBtn = document.querySelector('#zfbBtn'),
      wxBtn = document.querySelector('#wxBtn');

    if (zfbBtn && wxBtn) {
      zfbBtn.addEventListener('click', () => {
        window.Velocity(zfb, 'transition.slideLeftIn', {
          duration: 400
        });
        window.Velocity(wx, 'transition.slideRightOut', {
          display: 'none',
          duration: 400
        });
      });

      wxBtn.addEventListener('click', () => {
        window.Velocity(wx, 'transition.slideRightIn', {
          duration: 400
        });
        window.Velocity(zfb, 'transition.slideLeftOut', {
          display: 'none',
          duration: 400
        });
      });
    }

    rewardBtn && rewardBtn.addEventListener('click', (e) => {
      window.Velocity(mask, 'transition.slideDownIn', {
        duration: 400
      })
    });

    close.addEventListener('click', (e) => {
      e.preventDefault();
      window.Velocity(mask, 'transition.slideUpOut', {
        duration: 400
      })
    })
  }()
</script>

  </div>
</body>

<input hidden id="copy" />
<script>
  !function () {
    let times = document.querySelectorAll('.publish-time');
    for (let i = 0; i < times.length; i++) {
      let date = times[i].dataset.t;
      let time = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
      if (time < 60) {
        str = time + '秒之前';
      } else if (time < 3600) {
        str = Math.floor(time / 60) + '分钟之前';
      } else if (time >= 3600 && time < 86400) {
        str = Math.floor(time / 3600) + '小时之前';
      } else if (time >= 86400 && time < 259200) {
        str = Math.floor(time / 86400) + '天之前';
      } else {
        str = times[i].textContent;
      }
      times[i].textContent = str;
    }
  }();
</script>

<script>
  let language = '';
  if (language !== '') {
    let map = new Map();
    if (language === 'en') {
      map.set('search', 'Search');
      map.set('category', 'Categories');
      map.set('article', 'Articles');
      map.set('tag', 'Tags');
      map.set('top', 'Top');
      map.set('publish', 'published');
      map.set('minute', ' minutes');
      map.set('read-more', 'Read More');
      map.set('view', 'View');
      map.set('words', ' words');
      map.set('category-in', 'category in');
      map.set('preview', 'Meta');
      map.set('index', 'Toc');
      map.set('no-archives', "You haven't created yet");
      map.set('archives', " articles in total");
      map.set('cloud-tags', " tags in total");
      map.set('copyright', "Copyright: ");
      map.set('author', "Author: ");
      map.set('link', "Link: ");
      map.set('leave-message', "Leave a message");
      map.set('format', "Links Format");
      map.set('site-name', "Name: ");
      map.set('site-link', "Link: ");
      map.set('site-desc', "Desc: ");
      map.set('stat', " related results, taking ");
      map.set('stat-time', " ms");
      map.set('site-img', "Image: ");
    }

    if (map.size > 0) {
      let lanElems = document.querySelectorAll('.language');
      lanElems.forEach(elem => {
        let lan = elem.dataset.lan, text = map.get(lan);
        if (elem.__proto__ === HTMLInputElement.prototype) {
          elem.placeholder = text
        } else {
          if (elem.dataset.count) {
            text = elem.dataset.count + text;
          }
          elem.textContent = text;
        }
      })
    }
  }
  //拿来主义(真香)^_^，Clipboard 实现摘自掘金 https://juejin.im/post/5aefeb6e6fb9a07aa43c20af
  window.Clipboard = (function (window, document, navigator) {
    var textArea,
      copy;

    // 判断是不是ios端
    function isOS() {
      return navigator.userAgent.match(/ipad|iphone/i);
    }
    //创建文本元素
    function createTextArea(text) {
      textArea = document.createElement('textArea');
      textArea.value = text;
      textArea.style.width = 0;
      textArea.style.height = 0;
      textArea.clientHeight = 0;
      textArea.clientWidth = 0;
      document.body.appendChild(textArea);
    }
    //选择内容
    function selectText() {
      var range,
        selection;

      if (isOS()) {
        range = document.createRange();
        range.selectNodeContents(textArea);
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textArea.setSelectionRange(0, 999999);
      } else {
        textArea.select();
      }
    }

    //复制到剪贴板
    function copyToClipboard() {
      try {
        document.execCommand("Copy")
      } catch (err) {
        alert("复制错误！请手动复制！")
      }
      document.body.removeChild(textArea);
    }

    copy = function (text) {
      createTextArea(text);
      selectText();
      copyToClipboard();
    };

    return {
      copy: copy
    };
  })(window, document, navigator);

  function copyCode(e) {
    if (e.srcElement.tagName === 'SPAN' && e.srcElement.classList.contains('copy-code')) {
      let code = e.currentTarget.querySelector('code');
      var text = code.innerText;
      if (e.srcElement.textContent === '复制成功') {
        return;
      }
      e.srcElement.textContent = '复制成功';
      (function (elem) {
        setTimeout(() => {
          if (elem.textContent === '复制成功') {
            elem.textContent = '复制代码'
          }
        }, 1000);
      })(e.srcElement)
      Clipboard.copy(text);
    }
  }

  let pres = document.querySelectorAll('pre');
  pres.forEach(pre => {
    let code = pre.querySelector('code');
    let copyElem = document.createElement('span');
    copyElem.classList.add('copy-code');
    copyElem.textContent = '复制代码';
    pre.appendChild(copyElem);
    pre.onclick = copyCode
  })

</script>
<script src="/media/js/motion.js"></script>


<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll/dist/smooth-scroll.polyfills.min.js"></script>
<script>
  var scroll = new SmoothScroll('a[href*="#"]', {
    speed: 200
  });
</script>



<script src="/media/js/cool.js"></script>



</html>